package com.southwind.springboottest.controller;

import com.southwind.springboottest.entity.School;
import com.southwind.springboottest.entity.repository.SchoolRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

//@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@RequestMapping("/School")
public class SchoolHandler {
    @Autowired(required = false)
    private SchoolRepository repository;

    @GetMapping("/FindAll")
    public List<School> findAll(){
        return repository.findAll();
    }

    @GetMapping("/FindAll/{page}/{size}")
    public Page<School> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return repository.findAll(pageable);
    }//分页

    @GetMapping("name/{page}/{size}")
    public Page<School> SelectName(
            @PathVariable("page") Integer page,
            @PathVariable("size") Integer size,
            @RequestParam(value = "name", defaultValue = "") String name){
        try {
         name = URLDecoder.decode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        name = "%"+name+"%";
        Pageable pageable = PageRequest.of(page-1,size);
        return repository.findByNameLike(pageable, name);
    }

    @GetMapping("province")
    public List<School> SelectPro(@RequestParam(value = "pro", defaultValue = "") String pro){
        try {
            pro = URLDecoder.decode(pro, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return repository.findByProvince(pro);
    }

    @GetMapping("type")
    public List<School> SelectType(@RequestParam(value = "type", defaultValue = "") String type){
        if (type.equals("985高校")){
            type = "985";
        }else if ((type.equals("211高校"))){
            type = "211";
        }
        try {
            type = URLDecoder.decode(type, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        type = "%"+type+"%";
        return repository.findByTypeLike(type);
    }


}
